<template>
  <div>
    <header style="margin: 50px auto;text-align: center">
      <h1>{{ newsTable.newsTitle }}</h1>
    </header>
    <el-divider>作者：{{author}}，浏览量：{{newsTable.views}}，发布时间：{{timestampToTime(newsTable.createTime)}}</el-divider>
    <div style="width: 80%;margin: auto;padding: 50px;">
      {{newsTable.content}}
    </div>
  </div>
</template>

<script>
import {newsDetail} from "@/api/news";
import {getDetails} from "@/api/user";

export default {
  name: "newsDetail",
  data(){
    return {
      author: '未知',
      newsTable: {
        newsTitle: '',
        creator: '',
        createTime: '',
        content: '',
        views: 0
      }
    }
  },
  methods:{
    timestampToTime (timestamp) {
      var date = new Date(timestamp) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    async getNewsDetails(id){
      const response = await newsDetail(id)
      console.log(response)
      this.newsTable = response.data
      const user = await getDetails(response.data.creator)
      if (this.isNull(user.data)){
        this.author = '一名未知用户'
      }else{
        this.author = user.data.username
      }
    },
    //判断数据是否为空值，为空返回true,有值为false
    isNull(data) {
      if (!data) return true;
      if (JSON.stringify(data) === '{}') return true;
      if (JSON.stringify(data) === '[]') return true;
      return false;
    }
  },
  mounted() {
    console.log('okay, we get the id here',this.$route.params.id)
    this.getNewsDetails(this.$route.params.id)
  }
}
</script>

<style scoped>

</style>
